suppressPackageStartupMessages(library("optparse"))
library("methods")
#suppressPackageStartupMessages(library("raster"))
#print("All Libraries loaded")
## Create the directory structure based on config
system(paste("mkdir -p Config",sep=""),wait=T) 
source("/lustre/mib-cri/carrol09/Work/MyPipe/Process10/RScripts/Workflow_Functions3.r")
#
WkgDir <- getwd()
#CreateDirStruct(WkgDir,"Config",PipeLineLocations)


ConfigOut <- file.path(WkgDir,"Config","config.ini")


option_list <- list(


  make_option(c("-c","--config"),type="character",help="The pipeline config file",default="/lustre/mib-cri/carrol09/Work/MyPipe/Process10/Config/config.ini"),
	make_option(c("-g","--genome"),type="character",help="The desired genome to be used"),

	make_option(c("--workingDirectory"),type="character",help="The desired genome to be used",default=""),
	make_option(c("--bamDirectory"),type="character",help="The desired genome to be used",default=""),
	make_option(c("--fastqDirectory"),type="character",help="The desired genome to be used",default=""),

	make_option(c("--addSLXIDs"),type="character",help="The desired genome to be used",default=""),
	make_option(c("--addSampleNames"),type="character",help="The desired genome to be used",default=""),
	make_option(c("--addProjects"),type="character",help="The desired genome to be used",default=""),

	make_option(c("--callMacsAll"),type="character",help="Call,QC and find motifs in Macs Peaks",default=""),
	make_option(c("--callMacsPeaks"),type="character",help="Call Macs Peaks",default=""),
	make_option(c("--callMacsMotifs"),type="character",help="Call Macs Motif",default=""),
	make_option(c("--callMacsPeakProfile"),type="character",help="Perform QC on Macs Peaks",default=""),
	
	
	make_option(c("--callSicerPeaks"),type="character",help="Call Sicer Peaks",default=""),
	make_option(c("--callSicerMotifs"),type="character",help="Call Sicer Motif",default=""),
	make_option(c("--callSicerPeakProfile"),type="character",help="Perform QC on Sicer Peaks",default=""),
	
	
	make_option(c("--callTPICsPeaks"),type="character",help="Call TPICs Peaks",default=""),
	make_option(c("--callTPICsMotifs"),type="character",help="Call TPICs Motif",default=""),
	make_option(c("--callTPICsPeakProfile"),type="character",help="Perform QC on TPICs Peaks",default="")	
	
	
)

opt <- parse_args(OptionParser(option_list=option_list,description="\tWelcome to the CRUK Cambridge Institute ChIP-seq Pipeline\n\tWritten by Tom Carroll\n\tSuraj Menon and Rory Stark\n\tthomas.carroll@cruk.cam.ac.uk",prog="ChIPseqPipeline"))
Res <- readIniFile(opt$config)
##Match Options and Config

namesVersusConfig <- tolower(names(opt))
for(i in 1:length(opt)){
  if(namesVersusConfig[i] %in% Res[,2]){
    if(opt[[i]] != ""){
      Res[Res[,2] %in% namesVersusConfig[i],3] <- opt[[i]]
    }
  }
}

Res[Res[,2] %in% "workingdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"")
Res[Res[,2] %in% "bamdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"bamFiles","")
Res[Res[,2] %in% "fastqdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"FQFiles","")
Res[Res[,2] %in% "tempdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"Temp","")
Res[Res[,2] %in% "locationsdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"Locations","")
Res[Res[,2] %in% "workflowdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"Workflow","")
Res[Res[,2] %in% "fraglengthdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"Fragment_Lengths","")

Res[Res[,2] %in% "macsdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"Peaks","Macs","")
Res[Res[,2] %in% "sicerdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"Peaks","Sicer","")
Res[Res[,2] %in% "tpicsdirectory" & Res[,3] %in% "",3] <- file.path(WkgDir,"Peaks","TPICs","")


#print(Res)
#if(Res[Res[,2] %in% "genome",3] == ""){
#  stop("Need to specify a Genome!")
  #exit()
#}
AllSections <- unique(Res[,1])
file.rename(ConfigOut,gsub(".ini","old.ini",ConfigOut))
file.create(ConfigOut,showWarnings=T)
for(i in 1:length(AllSections)){
  write.table(paste("[",AllSections[i],"]",sep=""),ConfigOut,col.names=F,row.names=F,quote=F,append=T)
  VariablesInSection <- as.vector(Res[Res[,1] %in% AllSections[i],2])
  for(j in 1:length(VariablesInSection)){
       Variable <- VariablesInSection[j]
       Value  <- as.vector(Res[Res[,1] %in% AllSections[i] & Res[,2] %in% VariablesInSection[j],3])
       write.table(paste(Variable,Value,sep=" = "),ConfigOut,col.names=F,row.names=F,quote=F,append=T)      
  }
  write.table("",ConfigOut,col.names=F,row.names=F,quote=F,append=T)      
}

SLXIDsFile <- file.path(Res[Res[,2] %in% "locationsdirectory",3],"SLXIDsFromLims.txt")
ProjectsFile <- file.path(Res[Res[,2] %in% "locationsdirectory",3],"ProjectsFromLims.txt")
SampleNamesFile <- file.path(Res[Res[,2] %in% "locationsdirectory",3],"SampleNamesFromLims.txt")

print(SLXIDsFile)

addSLXIDs <- opt$addSLXIDs
if(addSLXIDs != ""){
  SLXIDs <- as.vector(unlist(strsplit(addSLXIDs,"\\s+")))
  if(file.exists(SLXIDsFile) & file.info(SLXIDsFile)$size > 0){
  print("mate")
    TempSLXIDs <- as.vector(read.delim(SLXIDsFile,sep="",h=F)[,1])
    write.table(unique(c(TempSLXIDs,SLXIDs)),SLXIDsFile,col.names=F,row.names=F,quote=F)
  }else{
    write.table(unique(c(SLXIDs)),SLXIDsFile,col.names=F,row.names=F,quote=F)
  }
}

addProjects <- opt$addProjects
if(addProjects != ""){
  Projects <- as.vector(unlist(strsplit(addProjects,"\\s+")))
  if(file.exists(ProjectsFile) & file.info(ProjectsFile)$size > 0){
    TempProjects <- as.vector(read.delim(ProjectsFile,sep="",h=F)[,1])
    write.table(unique(c(TempProjects,Projects)),ProjectsFile,col.names=F,row.names=F,quote=F)
  }else{
    write.table(unique(c(Projects)),ProjectsFile,col.names=F,row.names=F,quote=F)
  }
}

addSampleNames <- opt$addSampleNames
if(addSampleNames != ""){
  SampleNames <- as.vector(unlist(strsplit(addSampleNames,"\\s+")))
  if(file.exists(SampleNamesFile) & file.info(SampleNamesFile)$size > 0){
    TempSampleNames <- as.vector(read.delim(SampleNamesFile,sep="",h=F)[,1])
    write.table(unique(c(TempSampleNames,SampleNames)),SampleNamesFile,col.names=F,row.names=F,quote=F)
  }else{
    write.table(unique(c(SampleNames)),SampleNamesFile,col.names=F,row.names=F,quote=F)
  }
}

print(opt)
